package com.ruoyi.yx.controller;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.web.service.WeChatService;
import com.ruoyi.framework.web.service.WeCosService;
import com.tencent.cloud.Credentials;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;

@RestController
@Api("腾讯COSapi")
@RequestMapping("/api/wxcos")
public class WXCosController {

    @Autowired
    private WeCosService weCosService;

    /**
     * 获取临时授权
     * @return
     * @throws Exception
     */
    @PostMapping("/getCredential")
    @ApiOperation("微信code登录")
    public R<Credentials> getCredential()throws Exception{
        return weCosService.getCredential();
    }

    /**
     * 获取sign url
     * @return
     * @throws Exception
     */
    @PostMapping("/getSignUrl")
    @ApiOperation("微信code登录")
    public R<String> getSignUrl()throws Exception{
        return weCosService.getSignUrl();
    }



    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload/avatar")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

            File tmpFile = new File(filePath,fileName.replace("profile/upload",""));
            String url = weCosService.upload(tmpFile);
            //删除本地文件
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }



}
